package org.soc.timesheet.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.soc.timesheet.custom.domain.filters.ProjectFilter;
import org.soc.timesheet.domain.Projects;
import org.soc.timesheet.server.domain.service.ProjectsService;
import org.soc.timesheet.server.domain.service.SubProjectsService;
import org.soc.timesheet.server.domain.service.TimesheetService;
import org.soc.timesheet.server.domain.service.UsersProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RequestMapping("/projectses")
@Controller
@RooWebScaffold(path = "projectses", formBackingObject = Projects.class)
@RooWebJson(jsonObject = Projects.class)
public class ProjectsController {

	@RequestMapping(value = "/{page}/{limit}", headers = "Accept=application/json", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Page<Projects>> findAll(
			@PathVariable("page") int page, @PathVariable("limit") int size,
			@RequestHeader(value="filters",required=false) String filters) throws Exception {
		PageRequest pageRequest = new PageRequest(page, size);
		if(filters!= null && !filters.equals("")){
			return findByFilters(filters, pageRequest);
		}
		return find(pageRequest);
	}


	


	@RequestMapping(value = "/{page}/{limit}/{sortField}-{dir}", headers = "Accept=application/json", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Page<Projects>> findAll(
			@PathVariable("page") int page, @PathVariable("limit") int size,
			@PathVariable("sortField") String property,
			@PathVariable("dir") String direction,
			@RequestHeader(value="filters",required=false) String filters) throws JsonParseException, JsonMappingException, IOException {
		Direction[] dirs = Direction.class.getEnumConstants();
		Direction dir = null;
		for (int i = 0; i < dirs.length; i++) {
			dir = dirs[i];
			if (dir.name().equals(direction.toUpperCase())) {
				break;
			}
		}
		Order order = new Order(dir, property);

		PageRequest pageRequest = new PageRequest(page, size, new Sort(order));
		if(filters!= null && !filters.equals("")){
			return findByFilters(filters, pageRequest);
		}
		return find(pageRequest);
	}

	private ResponseEntity<Page<Projects>> find(PageRequest pageRequest) {
		HttpHeaders headers = getHeaders();
		Page<Projects> result = projectsService.findAll(pageRequest);
		return new ResponseEntity<Page<Projects>>(result, headers,
				HttpStatus.OK);
	}
	private ResponseEntity<Page<Projects>> findByFilters(String filters,
			PageRequest pageRequest) throws IOException, JsonParseException,
			JsonMappingException {
		ObjectMapper mapper = new ObjectMapper();
		ProjectFilter filter = mapper.readValue(filters, new TypeReference<ProjectFilter>() {
		});
		Page<Projects> page =  projectsService.findByFilters(filter,pageRequest);
		return new ResponseEntity<Page<Projects>>(page, getHeaders(),
				HttpStatus.OK);
	}
	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		return headers;
	}

	@Autowired
    ProjectsService projectsService;

	@Autowired
    SubProjectsService subProjectsService;

	@Autowired
    TimesheetService timesheetService;

	@Autowired
    UsersProjectService usersProjectService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Projects projects, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, projects);
            return "projectses/create";
        }
        uiModel.asMap().clear();
        projectsService.saveProjects(projects);
        return "redirect:/projectses/" + encodeUrlPathSegment(projects.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Projects());
        return "projectses/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Integer id, Model uiModel) {
        uiModel.addAttribute("projects", projectsService.findProjects(id));
        uiModel.addAttribute("itemId", id);
        return "projectses/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("projectses", Projects.findProjectsEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) projectsService.countAllProjectses() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("projectses", Projects.findAllProjectses(sortFieldName, sortOrder));
        }
        return "projectses/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Projects projects, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, projects);
            return "projectses/update";
        }
        uiModel.asMap().clear();
        projectsService.updateProjects(projects);
        return "redirect:/projectses/" + encodeUrlPathSegment(projects.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Integer id, Model uiModel) {
        populateEditForm(uiModel, projectsService.findProjects(id));
        return "projectses/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Integer id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Projects projects = projectsService.findProjects(id);
        projectsService.deleteProjects(projects);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/projectses";
    }

	void populateEditForm(Model uiModel, Projects projects) {
        uiModel.addAttribute("projects", projects);
        uiModel.addAttribute("subprojectses", subProjectsService.findAllSubProjectses());
        uiModel.addAttribute("timesheets", timesheetService.findAllTimesheets());
        uiModel.addAttribute("usersprojects", usersProjectService.findAllUsersProjects());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> showJson(@PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            Projects projects = projectsService.findProjects(id);
            if (projects == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(projects.toJson(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            List<Projects> result = projectsService.findAllProjectses();
            return new ResponseEntity<String>(Projects.toJsonArray(result), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJson(@RequestBody String json, UriComponentsBuilder uriBuilder) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            Projects projects = Projects.fromJsonToProjects(json);
            projectsService.saveProjects(projects);
            RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
            headers.add("Location",uriBuilder.path(a.value()[0]+"/"+projects.getId().toString()).build().toUriString());
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJsonArray(@RequestBody String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            for (Projects projects: Projects.fromJsonArrayToProjectses(json)) {
                projectsService.saveProjects(projects);
            }
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json, @PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            Projects projects = Projects.fromJsonToProjects(json);
            projects.setId(id);
            if (projectsService.updateProjects(projects) == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public ResponseEntity<String> deleteFromJson(@PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            Projects projects = projectsService.findProjects(id);
            if (projects == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            projectsService.deleteProjects(projects);
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
